/*

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/
#import "MediaQueueView.h"
#import "XBMCControlApplication.h"
#import "XBMCHttpInterface.h"
#import "MediaItem.h"
#import <UIKit/UITableView.h>

@implementation MediaQueueView

- (id) initWithApplication: (UIApplication*)app withAppID: (NSString*)appID withFrame: (struct CGRect)rect
{
    self = [super initWithFrame: rect];
	m_viewIsActive = NO;
	m_rect = rect;
	m_xbmc = [XBMCHttpInterface sharedInstance];
	m_mainApp = (XBMCControlApplication*)app;
	m_CellArray = [[NSMutableArray alloc] init];
	m_MediaItemArray = [[NSMutableArray alloc] init];
    m_table = [[UITable alloc] initWithFrame: CGRectMake(0.0f, 48.0f, rect.size.width, rect.size.height - 48.0f)];
	[self addSubview: m_table];
	UITableColumn *col = [[UITableColumn alloc] initWithTitle: @"XBMC Playlist"
        identifier: @"xbmc" width: rect.size.width];
    [m_table addTableColumn: col];
	
	[m_table setDataSource: self];
    [m_table setDelegate: self];
	[m_table setAllowsReordering: YES];
	[m_table setAllowSelectionDuringRowDeletion:YES];
	[m_table setShowScrollerIndicators:YES];
	m_isEditing = NO;
	
	// nav bar
    m_navBar = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, rect.size.width, 48.0f)] autorelease];
    [m_navBar showLeftButton:@"Main Menu" withStyle:0 rightButton:@"Refresh" withStyle:3];
    [m_navBar setBarStyle:0];
    [m_navBar setDelegate:self];
	[self addSubview: m_navBar];
	
	// create, offscreen
	m_bottomNavBar = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, rect.size.height, rect.size.width, 48.0f)] autorelease];
    [m_bottomNavBar setBarStyle:0];
	[self addSubview: m_bottomNavBar];
	float segWidth = 300.0f;
	m_bottomButtonPanelMusicItemRect = CGRectMake(320.0f / 2.0f - (segWidth / 2.0f), 6.0f, segWidth, 30.0f);
	m_bottomButtonPanelMusicItem = [[UISegmentedControl alloc] initWithFrame:m_bottomButtonPanelMusicItemRect withStyle:2 withItems:nil];
	[m_bottomButtonPanelMusicItem insertSegment:0 withTitle:@"Play" animated:NO];
	[m_bottomButtonPanelMusicItem insertSegment:1 withTitle:@"Get Info" animated:NO];
	[m_bottomButtonPanelMusicItem insertSegment:2 withTitle:@"Edit/Reorder" animated:NO];
	[m_bottomButtonPanelMusicItem setMomentaryClick:YES];
	[m_bottomButtonPanelMusicItem setDelegate:self];
	[m_bottomNavBar addSubview: m_bottomButtonPanelMusicItem];
		
	m_isBottomBarShown = false;
	
	UINavigationItem *title = [[[UINavigationItem alloc] initWithTitle:@"Media Queue"] autorelease];
    [m_navBar pushNavigationItem:title];


	return self;
}

-(void)dealloc
{
   [super dealloc];
}


- (void)tableRowSelected:(NSNotification *)notification 
{
	int i = [m_table selectedRow];
	NSLog(@"tableRowSelected!  %d", i);
	if( [m_table isRowDeletionEnabled] ) 
	{
		UIImageAndTextTableCell *cell = [m_CellArray objectAtIndex: i];
		[cell setSelected: YES];
		[cell setEnableReordering:YES animated:YES];
		[m_table _beginReorderingForCell:cell];
	}
	else
	{
		  [self hideBottomNavBar];
		  if (i != NSNotFound)
		  {
		      NSLog(@"valid selection");
			  MediaItem* item = [m_MediaItemArray objectAtIndex:i];
			  NSLog(@"got item");
			  if ([item getType] == kFolder)
			  {
			     NSLog(@"is folder");
			     // navigate to folder
			  }
			  else if ([item getType] == kPlaylist)
			  {
			     // display bottom
				 [self showBottomNavBar];
				 //[self showPlaylistButtons];
			  }
			  else if ([item getType] == kMusic || [item getType] == kVideo)
			  {
			     // display bottom
				 [self showBottomNavBar];
				 [self showMediaItemButtons];
			  }
			  
		  }
  }
}



- (void) segmentedControl: (UISegmentedControl *)segment selectedSegmentChanged: (int)seg
{
	if (segment == m_bottomButtonPanelMusicItem)
	{
	    NSLog(@"Selected segm3ent: MusicItem %i", seg);
		switch (seg)
		{
			case 0:  
				{
				   // play
				   int i = [m_table selectedRow];
				   if (i != NSNotFound)
				   {
				      [m_xbmc setPlaylistSong:i];
				   }
				}
				break;
			
			case 1:
				{
				   // get info
				   int i = [m_table selectedRow];
				   NSLog(@"table selected row %i", i);

				   if (i != NSNotFound)
				   {
				      NSLog(@"doing getInfo");
					  MediaItem* item = [m_MediaItemArray objectAtIndex:i];
					  NSMutableDictionary* itemInfo = [m_xbmc getFileInfo: [item getPath]];
					  // display artist, title, album
					  NSArray* buttons = [NSArray arrayWithObjects:@"Close",nil];
					  UIAlertSheet* popup = [[UIAlertSheet alloc] initWithTitle:@"File Info" buttons:buttons defaultButtonIndex:0 delegate:self context:nil];
					  NSString* body = [NSString stringWithFormat:@"Title: %@\nArtist: %@\nAlbum: %@",
						[itemInfo valueForKey:@"Title"],
						[itemInfo valueForKey:@"Artist"],
						[itemInfo valueForKey:@"Album"]];
					  [popup setBodyText: body];
					  [popup popupAlertAnimated: TRUE];
				   }
				}
				break;
			case 2:
				{
					if (!m_isEditing)
					{
						[m_table enableRowDeletion:YES animated:YES];
						[segment setTitle: @"Done" forSegment: seg];
						m_isEditing = YES;
					}
					else
					{
						[m_table enableRowDeletion:NO animated:YES];
						[segment setTitle: @"Edit/Reorder" forSegment: seg];
						m_isEditing = NO;
					}
					
				}
				
		}
	}
	
}

// return NO if you only want to move rows
- (BOOL)table:(UITable*)table canDeleteRow:( int)row {
	NSLog(@"canDeleteRow: %d",row);
	return YES;
}

// this method must be declared so that rows can be moved
// if you don't want to delete rows, then return NO from table:canDeleteRow:
- (void)table:(UITable*)table deleteRow:(int)row {
	NSLog(@"deleteRow: %d",row);
	// [m_xbmc deleteSong];
}

// this is requires to move rows, otherwise only the delete button object is shown
- (BOOL)table:(UITable*)table canMoveRow:(int)row{
	NSLog(@"canMoveRow: %d",row);
	return YES;
}

-(int)table:(UITable*)table movedRow:(int)row toRow:(int)dest{
	NSLog(@"movedRow: %d to %d",row, dest);
	return dest;
}

- (int) table:(UITable *) table moveDestinationForRow:(int)row withSuggestedDestinationRow:(int) suggestedRow {
	NSLog(@"moveDestinationForRow: %d to %d",row, suggestedRow);
	return suggestedRow;
}

- (BOOL) table:(UITable *) table canSelectRow:(int) row {
	NSLog(@"canSelectRow: %d ",row);
	return YES;
}

-(void) tableWillBeginMovingRow: (id) fp8
{
	NSLog(@"tableWillBeginMovingRow");
}


- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button 
{
	[sheet dismissAnimated: TRUE];
}

-(void)showBottomNavBar
{
   if (m_isBottomBarShown == NO)
   {
      [m_table setFrame:CGRectMake(0.0f, 48.0f, m_rect.size.width, m_rect.size.height - 96.0f)];
	  [m_bottomNavBar setFrame:CGRectMake(0.0f, m_rect.size.height - 48.0, m_rect.size.width, 48.0f)];
	  m_isBottomBarShown = YES;
	}
}

-(void)hideBottomNavBar
{
   if (m_isBottomBarShown == YES)
   {
      [m_table setFrame:CGRectMake(0.0f, 48.0f, m_rect.size.width, m_rect.size.height - 48.0f)];
   	  [m_bottomNavBar setFrame:CGRectMake(0.0f, m_rect.size.height, m_rect.size.width, 48.0f)];

	  m_isBottomBarShown = NO;
   }
}

-(void)showMediaItemButtons
{
   [m_bottomButtonPanelMusicItem setFrame:m_bottomButtonPanelMusicItemRect];
   [m_bottomButtonPanelPlaylist setFrame:
      CGRectMake(m_bottomButtonPanelPlaylistRect.origin.x, m_bottomButtonPanelPlaylistRect.origin.y+100,
	  m_bottomButtonPanelPlaylistRect.size.width, m_bottomButtonPanelPlaylistRect.size.height)];
}


-(void)refreshView
{
    [m_mainApp showProgress: YES];
	[self clearTable];
	int playlistIndex = [m_xbmc getCurrentPlaylistIndex];
	if (playlistIndex >= 0)
	{
		NSArray* playlistContents = [m_xbmc getCurrentPlaylistContents];
		int i;
		for(i=0; i<[playlistContents count]; ++i)
		{
			MediaItem *item = [playlistContents objectAtIndex:i];
			UIImageAndTextTableCell *cell = [[UIImageAndTextTableCell alloc] initWithFrame:CGRectMake(0.0f, 48.0f, m_rect.size.width, 48.0f)];
		    [cell setTitle:[item getName]];
		    [cell setShowDisclosure:NO];
		    [cell setSelected:NO];
			[cell setEnableReordering:YES animated:YES];
		    [m_CellArray addObject:cell];
			[m_MediaItemArray addObject:[item retain]];
		}
		[m_table selectRow:NSNotFound byExtendingSelection:NO withFade:NO];
		[m_table reloadData];
		
		int songIndex = [m_xbmc getPlaylistSong];
		if (songIndex != -1)
		{
			[m_table selectRow:songIndex byExtendingSelection:NO withFade:NO];
			[m_table scrollRowToVisible:songIndex];
		}
   }
   [m_mainApp showProgress: NO];
   NSLog(@"refreshView done");
}

-(void)activateView
{
   NSLog(@"activateView");
   if (m_viewIsActive == NO)
   {
      [self refreshView];
	   m_viewIsActive = YES;
   }
   NSLog(@"activateView done");
}

-(void)deactivateView
{
   if (m_viewIsActive == YES)
   {
	   [self clearTable];
	   [m_table reloadData];
	   m_viewIsActive = NO;
   }
}

-(void)clearTable
{
   int i;
   for (i=0; i<m_CellArray.count; ++i)
   {
	  [[m_CellArray objectAtIndex:i] release];
   }
   [m_CellArray removeAllObjects];
   for (i=0; i<m_MediaItemArray.count; ++i)
   {
	  [[m_MediaItemArray objectAtIndex:i] release];
   }
   [m_MediaItemArray removeAllObjects];
}

-(UITable*)table
{
   return m_table;
}

- (int) numberOfRowsInTable: (UITable *)table
{
    return [m_CellArray count];
}

- (UITableCell *) table: (UITable *)table cellForRow: (int)row column: (int)col
{
	return [m_CellArray objectAtIndex:row];
}

- (void)navigationBar:(id)navbar buttonClicked:(int)button
{
    if (navbar == m_navBar)
	{
	    switch (button)
	    {
	        case 0:
	            [self refreshView];
	            break;
	        case 1:
	            // transition to main menu
				[m_mainApp transitionToMainMenu];
	            break;
	    }
	}
}

- (BOOL)respondsToSelector:(SEL)selector {
  NSLog(@"respondsToSelector: %s", selector);
  return [super respondsToSelector:selector];
}

@end

